package com.health.ts.config;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.health.ts.entity.sysmanage.SysAuthority;
import com.health.ts.entity.sysmanage.SysUser;
import com.health.ts.service.sysmanage.SysUserService;

@Component
public class UserRealm extends AuthorizingRealm {

	/**
	 * 用户信息服务
	 */
	@Autowired
	SysUserService sysUserService;

    /**
     * 用户验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取用户信息
        String username = authenticationToken.getPrincipal().toString();
        // 查询用户信息
	    SysUser user=sysUserService.selectUserByName(username);
        if (user == null) {
            //这里返回后会报出对应异常
        	 throw new UnknownAccountException();
        } else {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPasswd(), getName());
            return simpleAuthenticationInfo;
        }
    }
    
    /**
     * 用户权限验证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
    	SysUser user = (SysUser) principalCollection.getPrimaryPrincipal();
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if(StringUtils.isNotBlank(user.getRole_id())) {
        	// 添加角色
            String[] userRoles = user.getRole_id().split(",");
            for(String role : userRoles) {
                simpleAuthorizationInfo.addRole(role);
            }
        	// 添加权限
            List<SysAuthority> authorityList = sysUserService.selectAuthorityByUser(user);
            for(SysAuthority authority : authorityList) {
            	simpleAuthorizationInfo.addStringPermission(authority.getId());
            }
        }
    	return simpleAuthorizationInfo;
    }
}
